var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require("express-session");

const multer = require("multer");
const upload = multer({ dest: './public/uploads' });

const proApi = require("./api/pro");
const bannerApi = require("./api/banner");
const userApi = require("./api/user");
const cartApi = require("./api/cart");
const orderApi = require("./api/order");
const searchApi = require("./api/search");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bannerRouter = require('./routes/banner');
var newsRouter = require('./routes/news');
var orderRouter = require('./routes/order');
var shppingRouter = require('./routes/shpping');
var proRouter = require('./routes/pro');
var userRouter = require('./routes/user');
var loginRouter = require('./routes/login');

var app = express();

app.all("*",(req,res,next)=>{
  // 允许所有来源
  res.header("Access-Control-Allow-Origin","*");
  // 允许的请求方式
  res.header("Access-Control-Allow-Methods","get,post");
  res.header("Access-Control-Allow-Headers",'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, token');
  next();
})


app.use(session({
  secret: '老子天下第一',   // 加密信息，可以随便写
  resave: false,      // 强制保存session，默认为true，建议设置为false
  saveUninitialized: true,    // 强制将未初始化的session存储，默认为true，建议为true
  cookie: { maxAge: 1000 * 60*30  }    // 过期时间，毫秒数
}))
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use("/api/pro",proApi);
app.use("/api/banner",bannerApi);
app.use("/api/user",userApi);
app.use("/api/cart",cartApi);
app.use("/api/order",orderApi);
app.use("/api/search",searchApi);
app.use(upload.any());
// app.use("/api/bannerr",bannerApi);

app.all("*",(req,res,next)=>{
  if(req.session.isLogin === "ok" || req.url === "/login" || req.url === "/login/guard"){
    next();
  }else{
    res.redirect("/login");
  }
})

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/pro', proRouter);
app.use('/banner', bannerRouter);
app.use('/news', newsRouter);
app.use('/order', orderRouter);
app.use('/shpping', shppingRouter);
app.use('/user', userRouter);
app.use('/login', loginRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
